<script setup lang="ts">
import { getPatient,addPatient,editPatient,delPatient } from '@/services/user';
import { PatientList,Patient } from '@/types/user';
import { computed, onMounted, ref } from 'vue';
import { FormInstance, showConfirmDialog, showSuccessToast, showToast } from 'vant';
import { useRoute } from 'vue-router';
import { idCardRules, nameRules } from '@/utils/rules';
import { useConsultStore } from '@/stores';
import { useRouter } from 'vue-router';
const list=ref<PatientList>([])
const getPatientList=async()=>{
 const res= await getPatient()
 list.value=res.data
 if(isChange.value && list.value.length){
  //默认选中第一个
  const defPatient=list.value.find(item=>item.defaultFlag===1)
  if(defPatient){
    patientId.value=defPatient.id
  }else{
    patientId.value=list.value[0].id
  }
 }

}
onMounted(()=>{
  getPatientList()
})
const options=[
  {label:'男',value:1},
  {label:'女',value:0},
]
const showRight=ref(false)
const showRightfn=(item?:Patient)=>{
  if(item){
    //编辑
    const {id,name,idCard, gender,defaultFlag}=item
    patient.value={id,name,idCard, gender,defaultFlag}
  }else{
    //添加
    //清空表单数据
    form.value?.resetValidation() //清空验证
    patient.value={...initPatient}
  }
  showRight.value=true
}

const initPatient:Patient={
  name:'',
  idCard:'',
  gender:1,
  defaultFlag:0
}
const patient=ref<Patient>(initPatient)
const defaultFlag=computed({
  get(){
    //根据 patient.value.defaultFlag的值当读取defaultFlag时显示true或者false
   return patient.value.defaultFlag===1?true:false
    },
  set(value){

    // 当要改写defaultFlag的值时通知 patient.value.defaultFlag讲值改成0或者1
    return patient.value.defaultFlag = value ? 1 : 0
  }
})
//表单验证提交
const form=ref<FormInstance>()
const onRightSubmit=async()=>{
  await form.value?.validate() //验证姓名和身份证号
  //身份证倒数第二位,单数是男,双数是女
  const gender=+patient.value.idCard.slice(-2,-1) %2
  if(gender!==patient.value.gender){
   await showConfirmDialog({
      title:'温馨提示',
      message:'选择的性别和身份证信息中的不一致\n您确认提交吗?'
    })
  }
  // 判断是编辑还是添加发请求
  patient.value.id? await editPatient(patient.value) : await addPatient(patient.value)

  showRight.value=false
  getPatientList()
  showSuccessToast( patient.value.id?'编辑成功' :'添加成功')
}
//删除患者
const delPatientFn=async()=>{
  //确认框 ,关闭图层,更新列表
  if(patient.value.id){
    await showConfirmDialog({
      title:'温馨提示',
      message:'确认删除 '+patient.value.name+'患者信息吗?'
    })
    await delPatient(patient.value.id)
    showRight.value=false
    getPatientList()
    showSuccessToast('删除患者信息成功')
  }
}
//添加患者
const route=useRoute()
const isChange=computed(()=>{
  return route.query.isChange ==='1'
})
const patientId=ref<string>()
const selectPatient=(item:Patient)=>{
  //只有在添加患者时才会触发
  if(isChange.value){
    patientId.value=item.id
  }
}
const store=useConsultStore()
const router=useRouter()
const next=()=>{
  if(!patientId.value){
    return showToast('请选择患者')
  }else{
    store.setPatientId(patientId.value)
    router.push('/consult/pay')
  }
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange? '添加患者':'家庭档案'"></cp-nav-bar>
      <!-- 头部提示 -->
      <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div class="patient-item" :class="{selected:patientId===item.id}" v-for="item in list" :key="item.id" @click="selectPatient(item)">
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{ item.idCard.replace(/^(.{6}).+(.{4})$/,'$1********$2') }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{item.age}}岁</span>
        </div>
        <div class="icon" @click.stop="showRightfn(item)"><cp-icon name="user-edit" /></div>
        <div class="tag" v-if="item.defaultFlag===1">默认</div>
      </div>

        <div class="patient-add" v-if="list.length<6" @click="showRightfn()">
           <cp-icon name="user-add" />
           <p>添加患者</p>
        </div>

      <div class="patient-tip">最多可添加 6 人</div>
        <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
    </div>
     <van-popup
      v-model:show="showRight"
      position="right"
    >
    <cp-nav-bar
    :title="patient.id?'编辑患者':'添加患者'"
    right-text="保存"
    :back="()=>showRight=false"
    @click-right="onRightSubmit"
    ></cp-nav-bar>
    <van-form autocomplete="off" ref="form">
        <van-field v-model="patient.name"   :rules="nameRules" label="真实姓名" placeholder="请输入真实姓名" />
        <van-field v-model="patient.idCard" :rules="idCardRules" label="身份证号" placeholder="请输入身份证号" />
        <van-field  label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn :options="options" v-model="patient.gender"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlag" :icon-size="18" round  />
          </template>
        </van-field>
      </van-form>

      <!-- 删除按钮 -->
      <van-action-bar v-if="patient.id">
            <van-action-bar-button  text="删除" @click="delPatientFn"/>
      </van-action-bar>

    </van-popup>
    </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }

  }
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}

.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
</style>
